<template>
  <div>
    <el-upload
      ref="upload"
      action="#"
      :show-file-list="false"
      :accept="accessFileType"
      :http-request="uploadFile"
      :before-upload="beforeUpload"
      v-if="type === 'edit'"
    >
      <template v-if="fileTypes">
        文件类型：
        <el-select
          v-model="fileType"
          placeholder="请选择"
          size="small"
          clearable
          allow-create
          filterable
          style="margin-right: 20px;"
        >
          <el-option
            v-for="(item, index) in fileTypes"
            :key="index"
            :value="item"
          ></el-option>
        </el-select>
        <!-- <el-select v-else v-model="fileType" size="small" style="margin-right: 20px;">
                  <el-option :value="fileType"></el-option>
                </el-select> -->
      </template>
      <slot></slot>
      <el-button
        size="small"
        type="primary"
        style="float: right;"
      >
        <i :class="uploading?'el-icon-loading':'el-icon-upload2'"></i>
        <span>上传文件</span>
      </el-button>
      <template #tip>
        <div
          class="el-upload__tip"
          v-if="showTip && type === 'edit'"
        >
          请上传
          <template v-if="maxFileSize"> 大小不超过 <b style="color: #f56c6c">{{ maxFileSize }}MB</b>
          </template>
          <template v-if="accessFileType"> 格式为 <b style="color: #f56c6c">{{ accessFileType }}</b>
          </template>
          的文件
        </div>
      </template>
    </el-upload>
    <el-table
      :data="fileList"
      ref="table"
      v-loading="tableLoading"
      stripe
      highlight-current-row
      border
      style="width: 100%;margin-top: 10px;"
    >
      <el-table-column
        label="序号"
        width="80"
      >
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column
        label="文件名称"
        show-overflow-tooltip
        prop="fileName"
      ></el-table-column>
      <el-table-column
        label="文件类型"
        width="200"
        prop="fileType"
      ></el-table-column>
      <el-table-column
        label="操作"
        width="150"
      >
        <template #default="scope">
          <div style="display: flex;justify-content: space-evenly;">
            <el-link
              type="primary"
              @click="downloadFile(scope.row)"
            >下载</el-link>
            <!--            <el-link type="primary" @click="previewFile(scope.row)">预览</el-link>-->
            <el-popconfirm
              title="确认删除该文件吗？"
              @confirm="deleteFile(scope.row)"
              v-if="type === 'edit'"
            >
              <template #reference>
                <el-link type="danger">删除</el-link>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as fileApi from '@/api/file'
import { download } from '@/utils/request'

export default {
  props: {
    // 大小限制(MB)
    maxFileSize: {
      type: Number
    },
    // 文件类型, 逗号分隔
    accessFileType: {
      type: String,
      default: 'pdf'
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: false
    },
    bizId: {
      type: [Number, String]
      // required: true
    },
    bizType: {
      type: [Number, String],
      required: true,
      default: 'CONTRACT'
    },
    // 业务侧自定义 eg：合同/附件
    fileTypes: {
      type: Array
    },
    // fileType和fileType二选一传入
    fileType: {
      type: String
    },
    title: {
      type: String,
      default: '文件信息'
    },
    type: {
      type: String,
      validator(value) {
        return ['edit', 'view'].includes(value)
      },
      default: 'edit'
    }
  },
  data() {
    return {
      fileList: [],
      uploading: false,
      tableLoading: false
    }
  },
  computed: {
    fileSize() {
      return this.maxFileSize * 1024 * 1024
    },
    showTip() {
      return this.isShowTip && (this.accessFileType || this.maxFileSize)
    }
  },
  watch: {
    bizId: {
      handler() {
        if (this.bizId) {
          this.getFileList()
        }
      },
      immediate: true
    }
  },
  methods: {
    uploadFile(params) {
      let newFile = new FormData()
      newFile.append('files', params.file)
      fileApi.uploadFile({
        bizId: this.bizId,
        bizType: this.bizType,
        fileType: this.fileType ?? ''
      }, newFile).then(res => {
        this.uploading = false
        if (res.code !== 200) {
          this.$modal.msgError('上传文件失败：{}', res.msg)
          return
        }
        this.getFileList()
      }).catch(() => this.uploading = false)
    },
    downloadFile(file) {
      download(`/file/download?bizId=${this.bizId}&bizType=${this.bizType}&fileType=${this.fileType}&fileName=${file.fileName}`, {}, file.fileName, {})
    },
    deleteFile(file) {
      fileApi.delFile({
        bizId: this.bizId,
        bizType: this.bizType,
        fileType: this.fileType,
        fileName: file.fileName
      }).then(res => {
        if (res.code !== 200) {
          this.$modal.msgError('下载文件失败：{}', res.msg)
          return
        }
        this.$modal.msgSuccess('成功删除文件')
        this.getFileList()
      })
    },
    previewFile(file) {
      fileApi.previewFile({
        bizId: this.bizId,
        bizType: this.bizType,
        fileName: file.fileName
      }).then(res => {
        if (res.code !== 200) {
          this.$modal.msgError('预览文件失败：{}', res.msg)
          return
        }
      })
    },
    beforeUpload(file) {
      if (this.uploading) {
        this.$modal.msgError('上传中，请稍后再试')
        return false
      }
      if (this.maxFileSize && file.size > this.fileSize) {
        this.$modal.msgError('文件大小超过限制')
        return false
      }
      this.uploading = true
    },
    getFileList() {
      this.tableLoading = true
      fileApi.queryFiles({
        bizId: this.bizId,
        bizType: this.bizType,
        fileType: this.fileTypes ? '' : this.fileType
      }).then(res => {
        if (res.code === 200) {
          this.fileList = res.data
          this.tableLoading = false
        } else {
          this.$modal.msgError('查询文件失败： {}', res.msg)
        }
      })
    }
  },
  // beforeMount() {
  //   this.getFileList()
  // },
  beforeDestroy() {
    Object.assign(this.$data, this.$options.data())
  }
}
</script>
